package io.decorated.byte_;

import java.io.*;

public class ObjectInputStream_ {
    //当保存值和数据类型时 就涉及到序列化
    //反序列化就是恢复值和数据类型
    //使类可以被序列化，必须实现两个接口之一：Serializable Externalizable

    public static void main(String[] args) {
        String filePath = "";//序列化后 保存的文件格式不是纯文本

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
            oos.writeInt(100);//int -> Integer
            oos.writeBoolean(true);//int -> Integer
            oos.writeChar('a');
            oos.writeDouble(9.5);
            oos.writeUTF("dddddd");

            //保存对象
            oos.writeObject(new Dog("小白", 3));

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

            //（读取）反序列化 顺序需要和保存数据（序列化）的顺序一致
            System.out.println(ois.readInt());
            //...
            Object dog = ois.readObject();
            System.out.println(dog.getClass());


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 序列化
     * 1.static和transient不会序列化
     * 2.类的属性也要求是序列化的
     * 3.序列化有继承性，也就是说，如果某类实现了序列化，则它的子类已经实现了序列化
     */
    static class Dog implements Serializable {
        private String name;
        private int age;
        private static String nation;//static和transient不会序列化
        private transient String color;

        public Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public Dog(String name,String nation, int age, String color) {
            this.name = name;
            this.nation = nation;
            this.age = age;
            this.color = color;
        }
    }
}
